import Crypto from './crypto.js';
import './hmac.js';
import './sha1.js';
import {
	Base64
} from './base64.js';
import {
	config
} from './config.js'


export default {
	_getPolicy() {
		let policyText = {
			"expiration": new Date(+new Date() + 30600000).toISOString(), //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
			"conditions": [
				["content-length-range", 0, config.uploadFileSize] // 设置上传文件的大小限制
			]
		};

		return Base64.encode(JSON.stringify(policyText))
	},
	_getSignature(message) {
		let bytes = Crypto.HMAC(Crypto.SHA1, message, config.AccessKeySecret, {
			asBytes: true
		});
		// const tmp = Crypto.util.bytesToBase64(bytes);
		return uni.arrayBufferToBase64(bytes);
	},
	_getSuffix(filename) {
		let pos = filename.lastIndexOf('.')
		let suffix = ''
		if (pos != -1) {
			suffix = filename.substring(pos)
		}
		return suffix;
	},
	uploadFile(filePath, fileType, path) {
		return new Promise((resolve, reject) => {
			const sign = this.get_STS()
			const fileName = this.getFileName(filePath, path)
			uni.uploadFile({
				url: sign.host,
				filePath,
				fileType,
				name: 'file',
				formData: {
					name: filePath,
					key: fileName,
					policy: sign.policy,
					OSSAccessKeyId: sign.accessId,
					success_action_status: '200',
					signature: sign.signature
				},
				success: res => {
					if (res.statusCode === 200) {
						resolve('/' + fileName)
					} else {
						reject(res)
					}
				},
				fail: err => {
					console.log(err);
					reject(err)
				}
			})
		});
	},
	getFileName(filename, path) {
		const timer = new Date()
		const fullFileName = timer.getTime() + Math.random().toString(36).substring(3, 20) + this._getSuffix(filename)
		return `${path || 'upload'}/${timer.getFullYear()}/${timer.getMonth() + 1}/${timer.getDate()}/${fullFileName}`
	},
	uploadImage(size = 1) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: size, 
				sizeType: ['original'],
				sourceType: ['album', 'camera'],
				success: async files => {
					uni.showLoading({
						title: '文件上传中...'
					})
					const promiseAll = []
					files.tempFilePaths.slice(0, size).forEach(item => {
						promiseAll.push(this.uploadFile(item, 'image'))
					})
					const urlList = await Promise.all(promiseAll).catch(err => {
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						})
					})
					uni.hideLoading()
					resolve(urlList)
				}
			})
		});
	},
	uploadVideo() {
		return new Promise((resolve, reject) => {
			uni.chooseVideo({
				count: 1,
				sourceType: ['camera', 'album'],
				success: res => {
					if (res.size > config.uploadFileSize) {
						uni.showToast({
							title: '文件大小超过系统上传限制：' + config.uploadFileSize,
							icon: 'none',
							duration: 1000
						});
						return;
					}
					this.uploadFile(res.tempFilePath, 'video').then(res => {
						resolve(res)
					})
				},
				fail: () => {
					uni.showToast({
						title: '取消选择视频',
						icon: 'none',
						duration: 2000
					});
				}
			})
		});
	},
	// 获取STS签名
	get_STS() {
		// 读取接口
		/* return new Promise((resolve, reject) => {
		    let name = new Date().getTime() + Math.random();
		    let operate = 'uploadImg';
		    let that = this;
		    uni.request({
		        method: "GET",
		        url: "*************",
		        data: {
		            name,
		            operate,
		            sign: Crypto.MD5(name + operate + "bayinabayin888").toString()
		        },
		        success(res) {
		            if (res.data.code != 200) {
		                that.$alert(res.data.message || res.data.msg)
		            } else {
		                resolve(res.data.data)
		            }
		        },
		        error(err) {
		            reject(err)
		        }
		    })
		}) */
		// 本地获取
		const policy = this._getPolicy();
		const res = {
			accessId: config.OSSAccessKeyId,
			host: config.uploadImageUrl, // 自己去申请
			policy,
			signature: this._getSignature(policy),
		};
		return res
	},
};
